package buchiguestbook;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.logging.Logger;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.repackaged.org.joda.time.DateTime;

import java.util.Date;
import javax.jdo.PersistenceManager;

import buchiguestbook.Greeting;
import buchiguestbook.PMF;

public class SignBuchiGuestBookServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(SignBuchiGuestBookServlet.class.getName());

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		
		String content = req.getParameter("content");
		Date date = new Date();
		Greeting greeting = new Greeting(user, content, date);
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		try {
			pm.makePersistent(greeting);
		} finally {
			pm.close();
		}
		
		if (content == null) {
			content = "(No greeting)";
		}
		if (user != null) {
			log.info("Greeting posted by user " + user.getNickname() + ": " + content);
		} else {
			log.info("Greeting poster by anonymously: " + content);
			System.out.println("Greeting poster by anonymously: " + content);
		}
		//resp.sendRedirect("/intl/ja/buchiguestbook.jsp");
		resp.sendRedirect("/buchiguestbook.jsp");
	}
	
	
}
